﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Weight.Model;
using Weight.Dal;
using Weight.Base.Utility;
using System.Data;
using Weight.Base;
using Weight.Model.ResultEntity;
using Weight.Model.ParamEntity;
using WeightSystem.Common;
using Weight.Bll.CardManage;
using Weight.Dal.CardManager;
using Weight.Dal.Dispatch;

namespace Weight.Bll
{
    /// <summary>
    /// 称重业务类
    /// </summary>
    public class BllWeight
    {
        private DalWeight dal = new DalWeight();

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public Tuple<bool,bool> Add(WeightEntity entity, WeightDataFrom dataFrom)
        {
            bool res = false;
            bool isWeightOver = false; 
            entity.ScaleNo = ServiceManager.SystemConfig.WeightConfig.ScaleModel.Value;
            entity.ScaleName = ServiceManager.SystemConfig.WeightConfig.ScaleModel.Name;
            entity.WeightDate = DateTime.Now.ToString("yyyy-MM-dd");
            entity.WeightTime = DateTime.Now.ToString("HH:mm:ss");
            if (dal.IsExistByPlateNum(entity.PlateNum, 1))
            {
                //二次过磅数据
                entity.WeightState = 2;
                entity.Count = 1;
                entity.UploadFlag = 2;
                res = dal.UpdateByTran(entity, dataFrom,ServiceManager.SystemConfig.WeightConfig.WeightConsumeTicketConfig.Value);
                isWeightOver = true;
            }
            else
            {
                if(!string.IsNullOrEmpty(entity.Id) && dal.IsExistById(entity.Id,1))
                {
                    entity.WeightState = 2;
                    entity.Count = 1;
                    entity.UploadFlag = 2;
                    res = dal.UpdateByTran(entity, dataFrom, ServiceManager.SystemConfig.WeightConfig.WeightConsumeTicketConfig.Value);
                    isWeightOver = true;
                }
                else
                {
                    //一次过磅数据
                    entity.Id = new GetIdHelper().GetGuid();
                    entity.UpdateFlag = 0;
                    entity.UploadFlag = 0;
                    entity.IsDel = false;

                    if (entity.Tare > 0 && entity.Gross > 0)
                    {
                        entity.WeightState = 2;
                        entity.Count = 1;
                        isWeightOver = true;
                    }
                    else
                    {
                        entity.WeightState = 1;
                        entity.Count = 0;
                    }
                    entity.ProNum = "";
                    res = dal.AddByTran(entity, dataFrom, ServiceManager.SystemConfig.WeightConfig.WeightConsumeTicketConfig.Value);
                }
              
            }

            return new Tuple<bool, bool>(res,isWeightOver);
        }

        /// <summary>
        ///更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Update(WeightEntity entity, WeightDataFrom weightDataFrom)
        {
            entity.UpdateFlag = 2;
            return    dal.UpdateByTran(entity, weightDataFrom, ServiceManager.SystemConfig.WeightConfig.WeightConsumeTicketConfig.Value);
        }

        /// <summary>
        /// 查询字段值
        /// </summary>
        /// <param name="field">字段</param>
        /// <returns></returns>
        public IEnumerable<string> QueryFieldVal(string field)
        {
            if (string.IsNullOrEmpty(field)) return new List<string>();
            return dal.QueryFieldVal(field);
        }

        /// <summary>
        /// 根据sql 
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataSet GetWeightDataBySql(string sql)
        {
            if (string.IsNullOrEmpty(sql)) return null;
            return dal.GetWeightDataBySql(sql);
        }

        /// <summary>
        /// 根据项目编号获取称重数据
        /// </summary>
        /// <param name="id">项目编号</param>
        /// <returns></returns>
        public DataTable GetDataById(string id)
        {
            if(string.IsNullOrEmpty(id))
            {
                return null;
            }
            else
            {
                return dal.GetDataById(id);
            }
        }

        /// <summary>
        /// 根据项目编号获取称重数据
        /// </summary>
        /// <param name="pronum">项目编号</param>
        /// <returns></returns>
        public DataTable GetDataByPronum(string pronum)
        {
            if (string.IsNullOrEmpty(pronum))
            {
                return null;
            }
            else
            {
                return dal.GetDataByPronum(pronum);
            }
        }

        /// <summary>
        ///查询称重数据
        /// </summary>
        /// <param name="reqParam"></param>
        /// <returns></returns>
       public DataSet SearchWeight(ReqQueryWeightReq reqParam)
        {
            return dal.WeightQueryData(reqParam);
        }

        /// <summary>
        ///查询称重数据
        /// </summary>
        /// <param name="reqParam"></param>
        /// <returns></returns>
        public DataSet SummaryWeight(SummaryWeightReq reqParam)
        {
            return dal.WeightSummaryData(reqParam);
        }

        /// <summary>
        /// 获取统计数据
        /// </summary>
        /// <returns></returns>
        public DataSet GetWeightAnalysis(SummaryWeightReq reqParam)
        {
           
            return dal.WeightSummaryData(reqParam);
        }

        /// <summary>
        /// 查询导出数据
        /// </summary>
        /// <param name="reqParam"></param>
        /// <returns></returns>
        public DataTable GetQueryExportData(ReqQueryWeightReq reqParam)
        {
            DataSet dtSet = dal.GetQueryExportData(reqParam);
            DataTable dt = dtSet.Tables[0];
           
            if (dtSet.Tables.Count > 1)
            {
                DataTable sumDt = dtSet.Tables[1];

                DataRow row = dt.NewRow();
                int index = DataTableHelper.GetDtFirstStringIndex(dt);
                if (index != -1)
                {
                    row.SetField(index, "合计:");
                }

                string columName = string.Empty;
                for (int i = 0; i < sumDt.Columns.Count; i++)
                {
                    columName = sumDt.Columns[i].ColumnName;
                    row.SetField(columName, sumDt.Rows[0][columName]);
                }
                dt.Rows.Add(row);
            }

            if (dt.Columns.Contains("Id"))
            {
                dt.Columns.Remove("Id");
            }
            return dt; 
        }


        /// <summary>
        /// 查询称重数据(没有合计)
        /// </summary>
        /// <param name="reqParam"></param>
        /// <returns></returns>
        public DataTable GetQueryWeightData(ReqQueryWeightReq reqParam)
        {
            DataSet dtSet = dal.GetQueryExportData(reqParam);
            DataTable dt = dtSet.Tables[0];
            return dt;
        }



        /// <summary>
        /// 获取最大的项目编号
        /// </summary>
        /// <param name="ScaleNo"></param>
        /// <returns></returns>
        public string GetMaxPronum(string ScaleNo)
        {
            return dal.GetMaxPronum(ScaleNo);
        }

        /// <summary>
        /// 获取称重数据
        /// </summary>
        /// <param name="id">编号</param>
        /// <param name="state">状态</param>
        /// <returns></returns>
        public Dictionary<string,string> GetWeightById(string id, int state)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
           if(string.IsNullOrEmpty(id))
            {
                return dic;
            }
           else
            {
                var entity =  dal.GetWeightById(id, state);
                if(entity != null)
                {
                    dic = ReflectHelper.ParseEntityToMap(entity);
                }
            }

            return dic;
        }

        /// <summary>
        /// 根据卡号获取称重数据
        /// </summary>
        /// <param name="cardNum"></param>
        /// <returns></returns>
        public Dictionary<string, string> GetWeightByCardNum(string cardNum, int state)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (string.IsNullOrEmpty(cardNum))
            {
                return dic;
            }
            else
            {
                var entity = dal.GetWeightByCardNum(cardNum, state);
                if (entity != null)
                {
                    dic = ReflectHelper.ParseEntityToMap(entity);
                }
            }
            return dic;
        }

        /// <summary>
        /// 根据车号获取称重数据
        /// </summary>
        /// <param name="plateNum">车号</param>
        /// <param name="state">状态</param>
        /// <returns></returns>
        public Dictionary<string, string> GetWeightByPlateNum(string plateNum, int state)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (string.IsNullOrEmpty(plateNum))
            {
                return dic;
            }
            else
            {
                var entity = dal.GetWeightByPlateNum(plateNum, state);
                if (entity != null)
                {
                    dic = ReflectHelper.ParseEntityToMap(entity);
                }
            }

            return dic;
        }

        /// <summary>
        /// 根据Id查询称重数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public WeightEntity GetWeightById(string id)
        {
            return  dal.GetWeightById(id, -1);
        }

        /// <summary>
        /// 获取查询字段
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        private string GetQueryField(List<WeightFieldEntity> field)
        {
            //生成查询字段
            var configField = ServiceManager.SystemConfig.WeightShowFields.Select(p => p.Field).ToList();
            var fields = field.Where(p => configField.Contains(p.Field)).ToList();
            fields.ForEach(p =>
            {
                var tmp = ServiceManager.SystemConfig.WeightShowFields.Where(t => t.Field == p.Field).FirstOrDefault();
                if (tmp != null)
                {
                    p.WeightShowOrder = tmp.Sort;
                }
            });
            field = fields.OrderBy(p => p.WeightShowOrder).ToList();

            StringBuilder fieldBuider = new StringBuilder();
            if (field != null && field.Count != 0)
            {
                var items = field.Where(p => p.IsWeightShow == true && p.Field != "待配置").OrderBy(p => p.WeightShowOrder).ToList();
                if (items.Count > 0)
                {
                    int index = 0;
                    foreach (var item in items)
                    {
                        if (string.IsNullOrEmpty(item.Field) || string.IsNullOrEmpty(item.Alias))
                        {
                            continue;
                        }
                        else
                        {
                            if (index > 0)
                            {
                                fieldBuider.Append(",");
                            }
                            fieldBuider.Append(item.Field).Append(" as [").Append(item.Alias).Append("]");
                            index++;
                        }
                    }

                }
                else
                {
                    fieldBuider.Append(" * ");
                }
            }
            else
            {
                fieldBuider.Append(" * ");
            }
            return fieldBuider.ToString();
        }
        /// <summary>
        /// 查询称重临时数据
        /// </summary>
        /// <param name="field"></param>
        /// <param name="plateNum"></param>
        /// <returns></returns>
        public DataTable QueryWeightTmpData(List<WeightFieldEntity> field, string plateNum,string dataSource)
        {
            string fieldStr = GetQueryField(field);
            return new DalWeight().QueryTmpData(fieldStr, plateNum, dataSource);
        }

        /// <summary>
        /// 查询称重临时数据
        /// </summary>
        /// <param name="field"></param>
        /// <param name="plateNum"></param>
        /// <returns></returns>
        public DataTable QueryInputWeightData(List<WeightFieldEntity> field, string dataSource)
        {
            string fieldStr = GetQueryField(field);
            return new DalWeight().QueryWeightData(fieldStr, dataSource);
        }

        /// <summary>
        /// 创建触发器
        /// </summary>
        /// <returns></returns>
        public bool CreateTriggerForPronum()
        {
           if(!dal.WeightTriggerIsExist())
            {
                return dal.CreateTriggerForPronum();
            }
           else
            {
                return true;
            }
            
        }
        /// <summary>
        /// 作废
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Tuple<bool,string> SetWeightDel(string id)
        {
            if(string.IsNullOrEmpty(id))
            {
                return new Tuple<bool, string>(false,"作废失败，Id无效");
            }
            if(dal.SetWeightDel(id))
            {
                return new Tuple<bool, string>(true,"作废成功");
            }
            else
            {
                return new Tuple<bool, string>(false,"作废失败");
            }
        }

        /// <summary>
        /// 指定卡号的一次过磅数据是否存在
        /// </summary>
        /// <param name="CardNum"></param>
        /// <returns></returns>
        public bool IsExistOnceWeightByCardId(string CardNum)
        {
            return dal.IsExistOnceWeightByCardId(CardNum);
        }

        /// <summary>
        /// 指定车号的一次过磅数据是否存在
        /// </summary>
        /// <param name="CardNum"></param>
        /// <param name="state">1 一次过磅，2二次过磅</param>
        /// <returns></returns>
        public bool IsExistByPlateNum(string plateNum, int state)
        {
            return dal.IsExistByPlateNum(plateNum, state);
        }

        /// <summary>
        /// 根据车号获取称重数据
        /// </summary>
        /// <param name="plateNum">车号</param>
        /// <param name="state">状态</param>
        /// <returns></returns>
        public WeightEntity GetByPlateNum(string plateNum, int state)
        {
            return dal.GetByPlateNum(plateNum,state);
        }

        /// <summary>
        /// 根据车号获取称重数据
        /// </summary>
        /// <param name="plateNum">车号</param>
        /// <returns></returns>
        public WeightEntity GetByPlateNum(string plateNum)
        {
            return dal.GetByPlateNum(plateNum);
        }

        /// <summary>
        /// 获取完成一次过磅的车辆信息
        /// </summary>
        /// <returns></returns>
        public int GetOnceWeightCount()
        {
            return dal.GetOnceWeightCount();
        }

        /// <summary>
        /// 获取完成过磅数量
        /// </summary>
        /// <returns></returns>
        public int GetOverWeightCount()
        {
            return dal.GetOverWeightCount();
        }

        /// <summary>
        /// 获取装卸货的数量
        /// </summary>
        /// <returns></returns>
        public int GetConfirmCount()
        {
            return dal.GetConfirmCount();
        }

        /// <summary>
        /// 获取条形图数据
        /// </summary>
        /// <returns></returns>
        public IEnumerable<MaterialPieChartRes> GetMaterialNetCollect()
        {
            return dal.GetMaterialNetCollect();
        }

        /// <summary>
        /// 获取饼形图数据
        /// </summary>
        /// <returns></returns>
        public IEnumerable<MaterialPieChartRes> GetMaterialCountCollect()
        {
            return dal.GetMaterialCountCollect();
        }
        
        /// <summary>
        /// 获取月趋势图
        /// </summary>
        /// <returns></returns>
        public IEnumerable<MaterialPieChartRes> GetMonthWeightCountCollect(string startDate, string endDate)
        {
            return dal.GetMonthWeightCountCollect(startDate,endDate);
        }


        /// <summary>
        /// 判断车号是否合规
        /// </summary>
        /// <param name="plateNum">车号</param>
        /// <param name="dataSourceFlag">获取</param>
        /// <returns></returns>
        public Tuple<bool,string> HasPlateNumInfo(string plateNum )
        {
            if(string.IsNullOrEmpty(plateNum))
            {
                return new Tuple<bool, string>(false,"车号为空,合法性验证失败");
            }

            // 判断车号是否有一次过磅记录
            var weightRes = IsExistByPlateNum(plateNum, 1);
            if(weightRes)
            {
                return new Tuple<bool, string>(true,"一次过磅记录存在,"+plateNum+" 验证合法;");
            }

            string dataSourceFlag = Convert.ToString(ServiceManager.SystemConfig?.WeightConfig?.WeightDataSource?.Value);

            // 判断车号发卡或派车单信息
            if (dataSourceFlag == "1")
            {
                
                var cardRes = new CardManagerDal().IsExistPlateNum(plateNum);
                if(cardRes)
                {
                    return new Tuple<bool, string>(true,"有未使用的发卡记录存在,"+plateNum+" 验证合法;");
                }
            }
            else if(dataSourceFlag == "2")
            {
                var disRes = new DalDispatch().PlateNumIsExist(plateNum);
                if (disRes)
                {
                    return new Tuple<bool, string>(true, "有未使用的发卡记录存在," + plateNum + " 验证合法;");
                }
            }

            return new Tuple<bool, string>(false, "车号验证不合法");
        }
    }
}
